package cn.bellychang.leetcode.question104;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Given the root of a binary tree, return its maximum depth.
 *
 * A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
 *
 * @author ChangLiang
 * @date 2021/2/7
 */
public class Solution {

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int currLevelSize = queue.size();
        int height = 0;
        int nextLevelSize = 0;
        int tempSize = 0;
        // loop invariant: not reach all null level
        while (currLevelSize != 0) {
            TreeNode treeNode = queue.poll();
            tempSize++;
            if (treeNode.left != null) {
                queue.offer(treeNode.left);
                nextLevelSize++;
            }
            if (treeNode.right != null) {
                queue.offer(treeNode.right);
                nextLevelSize++;
            }
            if (tempSize == currLevelSize) {
                height++;
                currLevelSize = nextLevelSize;
                tempSize = 0;
                nextLevelSize = 0;
            }
        }
        return height;
    }


}
